import { WeiQiMusic } from './WeiQi'

export default class Music implements WeiQiMusic {
  private goAudio: HTMLAudioElement | null
  private eatAudio: HTMLAudioElement | null
  private isSpeaking: boolean

  public constructor() {
    this.goAudio = null
    this.eatAudio = null
    this.isSpeaking = false
  }

  public release(): void {
    this.goAudio?.parentElement?.removeChild(this.goAudio)
    this.eatAudio?.parentElement?.removeChild(this.eatAudio)
    this.goAudio = null
    this.eatAudio = null
  }

  public set goSrc(src: string) {
    if (!this.goAudio) {
      this.goAudio = document.createElement('audio')
      document.querySelector('head')?.appendChild(this.goAudio)
    }
    this.goAudio.src = src
  }

  public set eatSrc(src: string) {
    if (!this.eatAudio) {
      this.eatAudio = document.createElement('audio')
      document.querySelector('head')?.appendChild(this.eatAudio)
    }
    this.eatAudio.src = src
  }

  private play(audio: HTMLAudioElement | null) {
    if (this.isSpeaking) return
    this.isSpeaking = true
    audio?.play()
    setTimeout(() => {
      this.isSpeaking = false
    }, 500)
  }

  public go(): void {
    this.play(this.goAudio)
  }

  public eat(): void {
    this.play(this.eatAudio)
  }
}